<!-- eslint-disable @typescript-eslint/no-unused-vars -->
<!--
 * @Description: 分享弹窗
 * @Author: Kerwin
 * @Date: 2023-09-20 11:50:40
 * @LastEditTime: 2025-03-10 11:27:04
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view>
    <hy-transition :mode-class="['fade']" :styles="maskClass" :duration="duration" :show="show" @click="closePop" />
    <hy-transition :mode-class="['slide-bottom']" :styles="transClass" :duration="duration" :show="show"
      @click="closePop">
      <view class="uni-share">
        <view class="tit">{{ hasRewrad ? "分享有奖（限领一次）" : "分享到" }}</view>
        <view class="uni-share-content">
          <view v-for="(item, index) in options" :key="index" class="uni-share-content-box" @click="handleShare(index)">
            <view class="uni-share-content-image">
              <!-- <u-icon
                :name="item.icon"
                :custom-prefix="'custom-icon'"
                class="content-image"
              /> -->
              <svg class="hy-icon content-image" aria-hidden="true">
                <use :xlink:href="item.icon"></use>
              </svg>
            </view>
            <!-- <text class="uni-share-content-text">{{ item.text }}</text> -->
            <view class="reward">{{ item.rewardValue || '' }}</view>
          </view>
        </view>
      </view>
    </hy-transition>
    <ShowImage ref="showImag"></ShowImage>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, watch } from 'vue'
import { onPageScroll, onReady } from '@dcloudio/uni-app'
import { launchClientApp } from '@/utils/common'
import ShowImage from '@/components/hy-image/index.vue' 
import {
  jsSdkConfig,
  updateAppMessageShareData,
  updateTimelineShareData
} from '@/common/wechat-share'
import { DOUYIN_CLIENT_KEY } from '@/common/config';
import { baseApi } from '@/api';
import { getImgFullPath, checkLoginState } from '../../utils/index';
import { isWeChat } from '../../utils/common';
import { useUserStore } from '@/store';

const userStore = useUserStore()
const props = withDefaults(
  defineProps<{
    shareData?: object,
  }>(),
  {
    shareData: () => {
      return {
        title: '',
        desc: '',
        link: '',
        imgUrl: ''
      }
    },
    showReward: true,
  }
)

const dataForSchema = reactive({
  nonce_str: '',
  timestamp: '',
  signature: ''
})
const getDouyinSign = async () => {
  if (userStore.checkLoginState()) {
    const { data } = await baseApi.getDouyinSignPost({
      refresh: false
    })
    console.log('getDouyinSign==>',data)
    dataForSchema.nonce_str = data.nonce_str
    dataForSchema.timestamp = data.timestamp
    dataForSchema.signature = data.signature
  }
}


const getDouyinSchema = (data: { nonce_str: string; timestamp: string; signature: string; video_path?: string }) => {
  // @ts-ignore
  const schema = window.dy_open_util.serialize({
    share_type: "h5",
    share_to_publish: 1,
    client_key: DOUYIN_CLIENT_KEY,
    nonce_str: data.nonce_str,
    timestamp: data.timestamp,
    signature: data.signature,
    video_path: data.video_path,
    hashtag_list: JSON.stringify(["hashtag1", "hashtag2"]),
    // micro_app_info: JSON.stringify({
    //   appId: "小程序appid",
    //   appTitle: "小程序title",
    //   description: "小程序描述语",
    //   appUrl: "pages/movie/index",
    // }),
  });
  console.log(schema, data);
  return schema;
}


const launchDouyin = (data: { video_path?: string | undefined; }) => {
  const schema = getDouyinSchema({ ...dataForSchema, ...data });
  // const schema = 'snssdk1128://webview?url=https%3A%2F%2Fopen.douyin.com%2Fplatform%2Foauth%2Fslink%2F%3Ftoken%3D5d1c2a56ac6bad6217a813d27dd4dbc7e2446452%26client_key%3Dawf4xgy8cibvhzuv';
  window.location.href = schema;
  const timer = setTimeout(() => {
    uni.showModal({
      content: '此功能需访问抖音客户端APP,请确保您已安装抖音客户端APP并登录',
      confirmText: '确定',
      success(res) {
        if (res.confirm) {
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }, 5000)
  window.addEventListener('visibilitychange', () => {
    const hidden =
      window.document.hidden ||
      window.document.mozHidden ||
      window.document.msHidden ||
      window.document.webkitHidden
    if (hidden) {
      clearTimeout(timer)
    }
  })
}


const options = reactive([
  {
    text: '好友',
    rewardKey: 'forwardFriendReward',
    rewardValue: null,
    type: 1,
    icon: '#icon-weixin',
    shareFn: updateAppMessageShareData
  },
  {
    text: '朋友圈',
    rewardKey: 'forwardFriendCircleReward',
    rewardValue: null,
    type: 2,
    icon: '#icon-pengyouquan',
    shareFn: updateTimelineShareData
  },
  {
    text: '抖音',
    rewardKey: 'forwardDouyinReward',
    rewardValue: null,
    type: 3,
    icon: '#icon-douyin',
    shareFn: launchDouyin
  },
])
const duration = ref(300)
const maskClass = reactive({
  position: 'fixed',
  bottom: 0,
  top: 0,
  left: 0,
  right: 0,
  backgroundColor: 'rgba(0, 0, 0, 0.4)',
  zIndex: 10000
})
const transClass = reactive({
  position: 'fixed',
  left: 0,
  right: 0,
  zIndex: 10001,
  bottom: 0
})
interface DynamicData {
  forwardDouyinReward?: any;
  forwardFriendCircleReward?: any;
  forwardFriendReward?: any;
  [propName: string]: any;
}
const dynamicData: DynamicData = ref({})
const show = ref(false)
const hasRewrad = ref(false)
const showPop = (data: DynamicData) => {
  dynamicData.value = data
  const _obj = data.user || {}
  let _rewardData = null
  const { forwardDouyinReward, forwardFriendCircleReward, forwardFriendReward } = _obj
  _rewardData = { forwardDouyinReward, forwardFriendCircleReward, forwardFriendReward }
  if (_rewardData) {
    for (const key in _rewardData) {
      const optionItem = options.find((item) => item.rewardKey === key)
      if (_rewardData[key] && optionItem) {
        // @ts-ignore
        optionItem.rewardValue = _rewardData[key] + '元/次'
        hasRewrad.value = true
      } else {
        optionItem && (optionItem.rewardValue = null)
        hasRewrad.value = false
      }
    }
  }
  console.log('分享组件',options)
  getDouyinSign()
  initJsSdk()
  show.value = true
}
const closePop = () => {
  show.value = false
}

//初始化weixinSdk
const initJsSdk = async () => {
  console.log('初始化，分享数据收集，点击分享第一步');
 userStore.getWxSdkConfig()
//  options[0].shareFn(props.shareData)
//  options[1].shareFn(props.shareData)
}


const showImag = ref<InstanceType<typeof ShowImage>>()
function handleShare(i: number) {
  console.log('点击其中分享小组件',i,props.shareData );
  
  if (options[i].type === 3) {
    launchDouyin({ video_path: getImgFullPath(dynamicData.value.videoUrl) })
  } else {
    // #ifdef H5
    if (!isWeChat()) {
      uni.showToast({
        title: '请在微信环境下分享',
        icon: 'none'
      })
      return
    }
    // #endif
    options[i].shareFn(props.shareData,showImag.value?.show)
  }
  emits('onSharedDate', options[i])
}
defineExpose({
  showPop,
  closePop
})
const emits = defineEmits(['onSharedDate'])
watch(() => props.shareData, (data:any) => {
  console.log('shareData分享:', data); // 调试信息
  try {
    // options[0].shareFn(data)
    // options[1].shareFn(data)
    options.forEach((e:any) =>{
      e.dynamicId = data.id
    })
  } catch (err) {
    console.log(err)
  }

  
})
</script>

<style lang="scss" scoped>
.uni-share {
  width: 690rpx;
  margin: 30rpx 30rpx calc(30rpx + env(safe-area-inset-bottom)) 30rpx;
  margin-left: auto;
  margin-right: auto;
  border-radius: 30rpx;
  /* #ifndef APP-NVUE */
  display: flex;
  flex-direction: column;
  /* #endif */
  background-color: #fff;

  .tit {
    font-size: 30rpx;
    padding: 20rpx 0 0 0;
    text-align: center;
  }

  .uni-share-content {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: center;
    overflow-x: scroll;
    padding: 15px 50rpx;

    .uni-share-content-box {
      /* #ifndef APP-NVUE */
      display: flex;
      /* #endif */
      flex-direction: column;
      align-items: center;
      // width: 25%;
      // justify-content: space-between;
      margin-right: 60rpx;

      &:nth-last-child(1) {
        margin-right: 0;
      }

      .uni-share-content-image {
        /* #ifndef APP-NVUE */
        display: flex;
        /* #endif */
        flex-direction: row;
        justify-content: center;
        align-items: center;
        width: 90rpx;
        height: 90rpx;
        overflow: hidden;
        border-radius: 10rpx;

        .content-image {
          width: 80rpx;
          height: 80rpx;
        }
      }

      // &:nth-last-child(1) {
      //   .uni-share-content-image .content-image {
      //     width: 50rpx !important;
      //     height: 50rpx !important;
      //   }
      // }

      .uni-share-content-text {
        font-size: 26rpx;
        color: #333;
        padding-top: 5px;
        padding-bottom: 10px;
      }
    }

    .reward {
      font-size: 26rpx;
      color: #666;
      padding-top: 10rpx;
    }
  }
}
</style>
